package com.longway.common.ws;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 消息通知
 */
@ServerEndpoint(value = "/msg/report.ws/{uid}")
public class MsgReportSocket {
	static String Url = "/msg/report.ws";
	protected static Log log = Log.getLog(MsgReportSocket.class);
	protected static ConcurrentLinkedQueue<MsgReportSocket> aueue = new ConcurrentLinkedQueue<>();
	private static final Map<String, Session> userSocketSessionMap;
	static {
		userSocketSessionMap = new HashMap<String, Session>();
	}

	// Socket

	public static ConcurrentLinkedQueue<MsgReportSocket> getAueue() {
		return aueue;
	}

	protected Session session;
	protected String userId;

	protected int count;

	@OnOpen
	public void onOpen(@PathParam("uid") String uid,Session session) {
		/*String sessionId = (String) config.getUserProperties().get(
				String.class.getName());*/
		this.session = session;
		this.userId = uid;
//		this.count = Db.queryInt("select count(id) from base_notice_object where objectType=1 and isRead=0 and userId=?",userId);
		aueue.add(this);
		System.out.println("有人进入请求报告大厅了，在线数：" + aueue.size());
		Map<String, Object> ret = new HashMap<>();
		ret.put("type", "1");
//		ret.put("count",  String.valueOf(this.count));
//		ret.put("text",  "积极分子待办");
//		ret.put("msg", "已连接到消息服务器!");

	        // 查询当前用户的任务、通知公告、站内条数信息条数
	        Map<String, String> noticeCount = new HashMap<String, String>();
	        List<Record> records = Db.find("SELECT count(objectType) as count,objectType,remark FROM base_notice_object WHERE isRead = 0 and userId=" + uid + " GROUP BY objectType,remark");
	       String taskCount = Db.queryStr("select count(1) from base_notice_object where userId = ? and isRead = 0",uid);
	        if (records.size() > 0) {
	            for (Record r : records) {
	                if ("1".equals(r.getStr("objectType"))) {
	                    noticeCount.put("taskCount", taskCount);
	                } else if ("2".equals(r.getStr("objectType"))) {
	                    noticeCount.put("noticeCount", r.getStr("count"));
	                } else if ("3".equals(r.getStr("objectType"))) {
	                    noticeCount.put("msgCode", r.getStr("count"));
	                }
	            }
	            ret.put("noticeCount", noticeCount);
	        } else {
	        	ret.put("noticeCount", "");
	        	ret.put("taskList", "");
	        }
	        ret.put("socketUrl", PropKit.get("socketUrl"));
		    sendMyMsg(JsonKit.toJson(ret));
	}

	@OnClose
	public void onClose() {
		aueue.remove(this);
		log.info("有人离开报告大厅了，在线数：" + aueue.size());
		System.out.println("有人离开报告大厅了，在线数：" + aueue.size());
	}


	/**
	 * 收到客户端消息后调用的方法
	 * 
	 * @param message
	 *            客户端发送过来的消息
	 * @param session
	 *            可选的参数
	 */
	@OnMessage
	public static void onMessage(String message, Session session) throws IOException {
		Map<String, Object> jsonTo = JSONObject.parseObject(message);
		List<JSONObject> userList=(List<JSONObject>) jsonTo.get("userList");
		System.out.println("来自客户端的消息:" + jsonTo);
		if (!jsonTo.get("To").equals("All")) {
			for (MsgReportSocket item : aueue) {
				for(JSONObject ss : userList){
				/**根据人员id发送*/
				if(ss.getString("userId").equals(item.userId)){
					Map<String, Object> map = new HashMap<String, Object>();
					List<Record> records1 = Db.find("select personnelTypeCode,COUNT(personnelTypeCode) count,remark from base_notice_object where objectType='1' and isRead=0 and userId=? GROUP BY personnelTypeCode,remark",item.userId);
					Map<String, String> noticeCount = new HashMap<String, String>();
					List<Record> records2 = Db.find("SELECT count(objectType) as count,objectType,remark FROM base_notice_object WHERE isRead = 0 and userId=" + item.userId + " GROUP BY objectType,remark");
					String taskCount = Db.queryStr("select count(id) from base_notice_object where userId = ? and isRead = 0",item.userId);
					if (records2.size() > 0) {
//			            for (Record r : records2) {
//			                if ("1".equals(r.getStr("objectType"))) {
//			                    noticeCount.put("taskCount", r.getStr("count"));
//			                } else if ("2".equals(r.getStr("objectType"))) {
//			                    noticeCount.put("noticeCount", r.getStr("count"));
//			                } else if ("3".equals(r.getStr("objectType"))) {
//			                    noticeCount.put("msgCode", r.getStr("count"));
//			                }
//			            }
						noticeCount.put("taskCount", taskCount);
			            map.put("noticeCount", noticeCount);
			            map.put("taskList", records1);
			            map.put("type", 1);
			        } else {
			        	noticeCount.put("taskCount", "0");
			        	map.put("noticeCount", noticeCount);
			        	map.put("taskList", "");
			        	 map.put("type", 1);
			        }
				item.sendMyMsg(JsonKit.toJson(map));
				}
			}
		}
		} else {/**群发*/
			for (MsgReportSocket item : aueue) {
				item.sendMyMsg(message);
			}
		}
	}

	
	
	
	protected void sendMyMsg(String msg) {
		try {
			
			this.session.getBasicRemote().sendObject(msg);
		} catch (Exception e) {
		}
	}


	protected void sendMyMsgMap(Map msg) {
		try {
			this.session.getBasicRemote().sendObject(msg);
		} catch (Exception e) {
		}
	}

	/**
	 * 给单个用户发送消息
	 */
	public void sendMsg(String userId,String count) {
		for (MsgReportSocket item : aueue) {
			/**根据人员id发送*/
			if(userId.equals(item.userId)){
			item.sendMyMsg(count);
			}
		}
	}

	/**
	 * 给单个用户发对象
	 */
	public void sendMsgMap(String userId,Map count) {
		for (MsgReportSocket item : aueue) {
			/**根据人员id发送*/
			if(userId.equals(item.userId)){
				item.sendMyMsgMap(count);
			}
		}
	}


	public String getUserId() {
		return userId;
	}

}
